﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.IO;
using LogLib;
using ComLib.ComFun;

namespace ComLib.ConfigService
{
    [Serializable]
    public abstract class SerializeBase : ISerializable, IConfig
    {
        [NonSerialized]
        protected string _error = "";

        [NonSerialized]
        private string _strConfigPath = "";

        [NonSerialized]
        private int _nVer = 0;

        [NonSerialized]
        protected int _nowVer = 0;

        public string ErrorMessage
        {
            protected set
            {
                _error = value;
                LoadingError.AddErrorMessage(value);
            }
            get { return _error; }
        }
      
        public string ConfigFilePath
        {
            get
            {
                if (string.IsNullOrEmpty(_strConfigPath))
                {
                    string className = this.GetType().Name;
                    _strConfigPath = Path.Combine(Paths.Directory, "config", className + ".dat");
                }
                return _strConfigPath;
            }
        }

        public int nVer
        {
            get { return _nVer; }
            set { _nVer = value; }
        }

        public SerializeBase()
        {

        }

        protected SerializeBase(SerializationInfo info, StreamingContext context)
        {
            _nVer = info.GetInt32("ver");
        }

        public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue("ver", _nVer);
        }

        public abstract bool Serialize();
        public abstract bool Load();
        public abstract bool LoadFrom(string path);
  
        public bool Save()
        {
            _error = "";
            if (!Serialize())
            {
                ErrorMessage = Serializer.Message;
                return false;
            }
            return true;
        }
    }
}

//public SerializeBase LoadAsObject()
//{
//    _error = "";
//    try
//    {
//        SerializeBase obj = (SerializeBase)Deserialize();             
//        return obj;
//    }
//    catch (Exception ex)
//    {
//        ErrorMessage = string.Format("配置文件{0}加载错误:\n\t{1}", ConfigFilePath, ex.Message);
//        Log.WriteException(ex.ToString());
//        return null;
//    }
//}